

import React, { useState, useEffect } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import styles from './styles.module.css';
import { FoodData, FoodDatabase } from './types';

const FoodDetailPage: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [selectedPortionIndex, setSelectedPortionIndex] = useState<number>(0);
  const [customPortionValue, setCustomPortionValue] = useState<string>('');
  const [selectedUnit, setSelectedUnit] = useState<string>('g');
  const [currentFoodData, setCurrentFoodData] = useState<FoodData | null>(null);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '食算 - 食物详情';
    return () => { document.title = originalTitle; };
  }, []);

  // 模拟食物数据库
  const foodDatabase: FoodDatabase = {
    "food1": {
      name: "鸡胸肉",
      category: "肉类 · 高蛋白食物",
      image: "https://s.coze.cn/image/m5P-2VDBxz4/",
      caloriesPer100g: 165,
      proteinPer100g: 31,
      carbPer100g: 0,
      fatPer100g: 3.6,
      commonPortions: [
        { unit: "g", value: 100, name: "100克", description: "标准份量" },
        { unit: "个", value: 1, name: "1个", description: "约150克" },
        { unit: "片", value: 1, name: "1片", description: "约50克" },
        { unit: "勺", value: 1, name: "1勺", description: "约25克" }
      ]
    },
    "food2": {
      name: "燕麦粥",
      category: "谷物 · 碳水化合物",
      image: "https://s.coze.cn/image/FG37ZWFV38o/",
      caloriesPer100g: 68,
      proteinPer100g: 1.9,
      carbPer100g: 12,
      fatPer100g: 1.5,
      commonPortions: [
        { unit: "g", value: 100, name: "100克", description: "标准份量" },
        { unit: "碗", value: 1, name: "1碗", description: "约150克" },
        { unit: "勺", value: 1, name: "1勺", description: "约20克" }
      ]
    },
    "food3": {
      name: "苹果",
      category: "水果 · 维生素",
      image: "https://s.coze.cn/image/sa9UUE5XtpI/",
      caloriesPer100g: 52,
      proteinPer100g: 0.3,
      carbPer100g: 14,
      fatPer100g: 0.2,
      commonPortions: [
        { unit: "g", value: 100, name: "100克", description: "标准份量" },
        { unit: "个", value: 1, name: "1个", description: "约150克" },
        { unit: "片", value: 1, name: "1片", description: "约30克" }
      ]
    }
  };

  // 加载食物数据
  useEffect(() => {
    const foodId = searchParams.get('foodId') || 'food1';
    const foodData = foodDatabase[foodId];
    if (foodData) {
      setCurrentFoodData(foodData);
    }
  }, [searchParams]);

  // 处理标准份量选择
  const handlePortionSelection = (index: number) => {
    setSelectedPortionIndex(index);
    setCustomPortionValue(''); // 清空自定义输入
  };

  // 处理自定义份量输入
  const handleCustomPortionChange = (value: string) => {
    setCustomPortionValue(value);
    if (value) {
      setSelectedPortionIndex(-1); // 表示选择了自定义份量
    } else {
      setSelectedPortionIndex(0); // 恢复默认选择
    }
  };

  // 计算营养成分
  const calculateNutrition = () => {
    if (!currentFoodData) return { calories: 0, protein: 0, carb: 0, fat: 0 };

    let portionValue = 100;
    let portionUnit = 'g';

    // 检查标准份量选择
    if (selectedPortionIndex !== -1 && currentFoodData.commonPortions[selectedPortionIndex]) {
      portionValue = currentFoodData.commonPortions[selectedPortionIndex].value;
      portionUnit = currentFoodData.commonPortions[selectedPortionIndex].unit;
    }

    // 检查自定义份量输入
    if (customPortionValue) {
      portionValue = parseFloat(customPortionValue);
      portionUnit = selectedUnit;
    }

    // 根据份量单位转换为克
    let weightInGrams = portionValue;
    if (portionUnit === '个') {
      weightInGrams = portionValue * 150;
    } else if (portionUnit === '片') {
      weightInGrams = portionValue * (currentFoodData.name === '苹果' ? 30 : 50);
    } else if (portionUnit === '勺') {
      weightInGrams = portionValue * (currentFoodData.name === '燕麦粥' ? 20 : 25);
    } else if (portionUnit === '碗') {
      weightInGrams = portionValue * 150;
    }

    // 计算营养成分
    const calories = Math.round(currentFoodData.caloriesPer100g * weightInGrams / 100);
    const protein = parseFloat((currentFoodData.proteinPer100g * weightInGrams / 100).toFixed(1));
    const carb = parseFloat((currentFoodData.carbPer100g * weightInGrams / 100).toFixed(1));
    const fat = parseFloat((currentFoodData.fatPer100g * weightInGrams / 100).toFixed(1));

    return { calories, protein, carb, fat };
  };

  // 获取当前份量信息
  const getCurrentPortionInfo = () => {
    if (!currentFoodData) return { value: 100, unit: 'g' };

    if (selectedPortionIndex !== -1 && currentFoodData.commonPortions[selectedPortionIndex]) {
      return {
        value: currentFoodData.commonPortions[selectedPortionIndex].value,
        unit: currentFoodData.commonPortions[selectedPortionIndex].unit
      };
    }

    if (customPortionValue) {
      return {
        value: parseFloat(customPortionValue),
        unit: selectedUnit
      };
    }

    return { value: 100, unit: 'g' };
  };

  // 处理返回按钮点击
  const handleBackClick = () => {
    navigate(-1);
  };

  // 处理添加到记录按钮点击
  const handleAddToRecord = () => {
    if (!currentFoodData) return;

    const nutrition = calculateNutrition();
    const portionInfo = getCurrentPortionInfo();

    alert(`即将添加到记录：\n${currentFoodData.name} ${portionInfo.value}${portionInfo.unit}\n卡路里：${nutrition.calories} kcal`);
  };

  // 处理搜索提交
  const handleSearchSubmit = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      navigate('/food-search');
    }
  };

  const nutrition = calculateNutrition();
  const portionInfo = getCurrentPortionInfo();

  if (!currentFoodData) {
    return <div className="flex items-center justify-center min-h-screen">加载中...</div>;
  }

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header className="fixed top-0 left-0 right-0 bg-white border-b border-border-light h-16 z-50">
        <div className="flex items-center justify-between h-full px-6">
          {/* Logo和产品名称 */}
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
              <i className="fas fa-utensils text-white text-sm"></i>
            </div>
            <h1 className="text-xl font-bold text-text-primary">食算</h1>
          </div>
          
          {/* 全局搜索框 */}
          <div className="flex-1 max-w-md mx-8">
            <div className="relative">
              <input 
                type="text" 
                placeholder="搜索食物..." 
                onKeyPress={handleSearchSubmit}
                className="w-full pl-10 pr-4 py-2 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
              <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
            </div>
          </div>
          
          {/* 右侧操作区 */}
          <div className="flex items-center space-x-4">
            {/* 消息通知 */}
            <button className="relative p-2 text-text-secondary hover:text-primary">
              <i className="fas fa-bell text-lg"></i>
              <span className="absolute -top-1 -right-1 w-3 h-3 bg-danger rounded-full"></span>
            </button>
            
            {/* 用户头像和下拉菜单 */}
            <div className="relative">
              <button className="flex items-center space-x-2 p-1 rounded-lg hover:bg-gray-100">
                <img 
                  src="https://s.coze.cn/image/VsGMrotf0bg/" 
                  alt="用户头像" 
                  className="w-8 h-8 rounded-full" 
                />
                <span className="text-sm text-text-primary">张三</span>
                <i className="fas fa-chevron-down text-xs text-text-secondary"></i>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* 左侧菜单 */}
      <aside className={`fixed left-0 top-16 bottom-0 w-60 bg-white border-r border-border-light z-40 ${styles.sidebarTransition}`}>
        <nav className="p-4">
          <ul className="space-y-2">
            <li>
              <Link to="/home" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-home text-lg"></i>
                <span className="font-medium">首页</span>
              </Link>
            </li>
            <li>
              <Link to="/food-search" className={`${styles.navItem} ${styles.navItemActive} flex items-center space-x-3 px-4 py-3 rounded-lg`}>
                <i className="fas fa-search text-lg"></i>
                <span className="font-medium">食物搜索</span>
              </Link>
            </li>
            <li>
              <Link to="/record-list" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-list text-lg"></i>
                <span className="font-medium">饮食记录</span>
              </Link>
            </li>
            <li>
              <Link to="/history" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-history text-lg"></i>
                <span className="font-medium">历史记录</span>
              </Link>
            </li>
            <li>
              <Link to="/settings" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-cog text-lg"></i>
                <span className="font-medium">设置</span>
              </Link>
            </li>
          </ul>
        </nav>
      </aside>

      {/* 主内容区 */}
      <main className="ml-60 mt-16 p-6 min-h-screen">
        {/* 页面头部 */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h2 className="text-2xl font-bold text-text-primary">食物详情</h2>
            <nav className="flex items-center space-x-2 text-sm text-text-secondary mt-1">
              <Link to="/food-search" className="hover:text-primary">食物搜索</Link>
              <i className="fas fa-chevron-right text-xs"></i>
              <span>食物详情</span>
            </nav>
          </div>
        </div>

        {/* 食物基本信息区 */}
        <section className="bg-white rounded-2xl shadow-card p-6 mb-8">
          <div className="flex items-center space-x-6">
            <img 
              src={currentFoodData.image} 
              alt={currentFoodData.name} 
              className="w-32 h-32 rounded-xl object-cover"
            />
            <div className="flex-1">
              <h3 className="text-2xl font-bold text-text-primary mb-2">{currentFoodData.name}</h3>
              <p className="text-sm text-text-secondary mb-4">{currentFoodData.category}</p>
              <div className="grid grid-cols-3 gap-4 text-center">
                <div className="bg-gray-50 rounded-lg p-3">
                  <p className="text-xs text-text-secondary mb-1">每100g</p>
                  <p className="text-lg font-bold text-text-primary">{currentFoodData.caloriesPer100g} kcal</p>
                </div>
                <div className="bg-gray-50 rounded-lg p-3">
                  <p className="text-xs text-text-secondary mb-1">蛋白质</p>
                  <p className="text-lg font-bold text-text-primary">{currentFoodData.proteinPer100g}g</p>
                </div>
                <div className="bg-gray-50 rounded-lg p-3">
                  <p className="text-xs text-text-secondary mb-1">脂肪</p>
                  <p className="text-lg font-bold text-text-primary">{currentFoodData.fatPer100g}g</p>
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* 份量选择区 */}
        <section className="bg-white rounded-2xl shadow-card p-6 mb-8">
          <h3 className="text-lg font-semibold text-text-primary mb-6">选择份量</h3>
          
          {/* 标准份量选择 */}
          <div className="mb-6">
            <label className="block text-sm font-medium text-text-primary mb-3">标准份量</label>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {currentFoodData.commonPortions.map((portion, index) => (
                <button
                  key={index}
                  onClick={() => handlePortionSelection(index)}
                  className={`${styles.portionSelector} px-4 py-3 border border-border-light rounded-lg text-center ${
                    selectedPortionIndex === index && !customPortionValue ? styles.portionSelectorActive : ''
                  }`}
                >
                  <p className="font-medium">{portion.name}</p>
                  <p className="text-xs text-text-secondary">{portion.description}</p>
                </button>
              ))}
            </div>
          </div>

          {/* 自定义份量输入 */}
          <div className="mb-6">
            <label className="block text-sm font-medium text-text-primary mb-3">自定义份量</label>
            <div className="flex items-center space-x-3">
              <input 
                type="number" 
                placeholder="输入份量" 
                value={customPortionValue}
                onChange={(e) => handleCustomPortionChange(e.target.value)}
                className="flex-1 px-4 py-3 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
              <select 
                value={selectedUnit}
                onChange={(e) => setSelectedUnit(e.target.value)}
                className="px-4 py-3 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              >
                <option value="g">克</option>
                <option value="ml">毫升</option>
                <option value="个">个</option>
                <option value="片">片</option>
                <option value="勺">勺</option>
              </select>
            </div>
          </div>

          {/* 份量图片参考 */}
          <div className="bg-gray-50 rounded-lg p-4 text-center">
            <p className="text-sm text-text-secondary mb-2">份量参考图</p>
            <img 
              src="https://s.coze.cn/image/CR24Bq_HoKw/" 
              alt="100克鸡胸肉参考图" 
              className="w-24 h-24 rounded-lg object-cover mx-auto"
            />
            <p className="text-xs text-text-secondary mt-2">
              {portionInfo.value}{portionInfo.unit} (约{getWeightInGrams(portionInfo.value, portionInfo.unit, currentFoodData)}克)
              {currentFoodData.name === '鸡胸肉' ? ' 约手掌大小' : 
               currentFoodData.name === '燕麦粥' ? ' 约半碗米饭的量' :
               currentFoodData.name === '苹果' ? ' 约中等大小苹果' : ''}
            </p>
          </div>
        </section>

        {/* 营养计算结果预览区 */}
        <section className="bg-white rounded-2xl shadow-card p-6 mb-8">
          <h3 className="text-lg font-semibold text-text-primary mb-6">营养计算结果</h3>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className={`${styles.nutritionCard} text-white rounded-lg p-4 text-center`}>
              <i className="fas fa-fire text-2xl mb-2"></i>
              <p className="text-xs opacity-90">卡路里</p>
              <p className="text-2xl font-bold">{nutrition.calories} kcal</p>
            </div>
            <div className="bg-blue-500 text-white rounded-lg p-4 text-center">
              <i className="fas fa-drumstick-bite text-2xl mb-2"></i>
              <p className="text-xs opacity-90">蛋白质</p>
              <p className="text-2xl font-bold">{nutrition.protein}g</p>
            </div>
            <div className="bg-yellow-500 text-white rounded-lg p-4 text-center">
              <i className="fas fa-bread-slice text-2xl mb-2"></i>
              <p className="text-xs opacity-90">碳水化合物</p>
              <p className="text-2xl font-bold">{nutrition.carb}g</p>
            </div>
            <div className="bg-red-500 text-white rounded-lg p-4 text-center">
              <i className="fas fa-oil-can text-2xl mb-2"></i>
              <p className="text-xs opacity-90">脂肪</p>
              <p className="text-2xl font-bold">{nutrition.fat}g</p>
            </div>
          </div>
        </section>

        {/* 操作按钮区 */}
        <section className="flex space-x-4">
          <button 
            onClick={handleAddToRecord}
            className="flex-1 bg-primary text-white py-4 rounded-lg hover:bg-indigo-600 transition-colors flex items-center justify-center space-x-2"
          >
            <i className="fas fa-plus"></i>
            <span>添加到记录</span>
          </button>
          <button 
            onClick={handleBackClick}
            className="px-8 py-4 border border-border-light text-text-primary rounded-lg hover:bg-gray-50 transition-colors"
          >
            <i className="fas fa-arrow-left mr-2"></i>
            返回
          </button>
        </section>
      </main>
    </div>
  );

  // 辅助函数：将份量转换为克
  function getWeightInGrams(portionValue: number, portionUnit: string, foodData: FoodData): number {
    let weightInGrams = portionValue;
    if (portionUnit === '个') {
      weightInGrams = portionValue * 150;
    } else if (portionUnit === '片') {
      weightInGrams = portionValue * (foodData.name === '苹果' ? 30 : 50);
    } else if (portionUnit === '勺') {
      weightInGrams = portionValue * (foodData.name === '燕麦粥' ? 20 : 25);
    } else if (portionUnit === '碗') {
      weightInGrams = portionValue * 150;
    }
    return weightInGrams;
  }
};

export default FoodDetailPage;

